package com.ihome.framework.core.nos;

import java.io.UnsupportedEncodingException;

import com.netease.cloud.services.nos.NosClient;
import com.netease.cloud.util.BinaryUtils;

/**
 * NOS认证相关的封装
 * 
 * @author zhengxiaohong
 */
public class NosAuthTool {

	/**
	 * 获取上传凭证
	 * 
	 * @param client
	 *            NOS客户端
	 * @param updatePolicy
	 *            上传策略
	 * @param accessKey
	 *            密钥对的公钥
	 * @return 上传凭证
	 */
	public static String getUploadToken(NosClient client, String updatePolicy, String accessKey) {
		String encodedUploadPolicy = null;
		try {
			encodedUploadPolicy = BinaryUtils.toBase64(updatePolicy.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		String encodedSign = client.signString(encodedUploadPolicy);
		String token = "UPLOAD " + accessKey + ":" + encodedSign + ":" + encodedUploadPolicy;
		return token;
	}

	/**
	 * 验证NOS回调的签名
	 * 
	 * @param nosClient
	 *            NOS客户端
	 * @param reqUrl
	 *            回调URL
	 * @param reqBody
	 *            回调请求的body
	 * @param encodedSign
	 *            回调请求中的签名
	 * @return 签名是否合法
	 */
	public static boolean validateStringSignature(NosClient nosClient, String reqUrl, String reqBody,
			String encodedSign) {
		byte[] data = null;
		try {
			data = (reqUrl + "\n" + reqBody).getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		String stringToSign = "NOS:" + BinaryUtils.toBase64(data);
		return nosClient.validateStringSignature(stringToSign, encodedSign);
	}

	/**
	 * 获取当前的Unix时间，单位秒
	 * 
	 * @return
	 */
	public static int currentTimeSeconds() {
		return (int) (System.currentTimeMillis() / 1000);
	}
}
